package com.jz.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.jz.Order;
import com.jz.Product;
import com.jz.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("order")
@Slf4j
public class OrderController {


    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private OrderService orderService;

    @GetMapping("createOrder/{pid}")
    @SentinelResource(fallback = "fallbackMethod",blockHandler = "blockHandlerMethod")
    public String createOrder(@PathVariable("pid")Integer pid){
        Order order=new Order();
        order.setUid(1);
        order.setUsername("张三");
        order.setNumber(1);
        Product product = restTemplate.getForObject("http://shop-product-sentinel/product/findById/" + pid, Product.class);
        if(product.getPid()==-1){
            return "服务正忙";
        }
        order.setPprice(product.getPprice());
        order.setPname(product.getPname());
        order.setPid(product.getPid());
        orderService.createOrder(order);
        return "下单成功";
    }

    public String fallbackMethod(Integer pid,Throwable e){
        return "调用了异常处理方法";
    }
    public String blockHandlerMethod(Integer pid, BlockException exception){
        return "调用了熔断降级的方法";
    }
}
